#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置管理模块
"""

import os
import json
from typing import Dict, Any


class Config:
    """配置管理类"""
    
    def __init__(self):
        self.load_config()
    
    def load_config(self):
        """加载配置"""
        # 默认配置
        self.MOCK_WX_CORP_ID = os.getenv('MOCK_WX_CORP_ID', 'wxc4c1ad1d26dc0daf')
        self.MOCK_WX_CORP_SECRET = os.getenv('MOCK_WX_CORP_SECRET', 'mock_secret_456')
        self.MOCK_OPEN_KF_ID = os.getenv('MOCK_OPEN_KF_ID', 'mock_kf_001')
        self.MOCK_TOKEN_EXPIRES = int(os.getenv('MOCK_TOKEN_EXPIRES', '7200'))
        self.MOCK_ENABLE_LOGGING = os.getenv('MOCK_ENABLE_LOGGING', 'true').lower() == 'true'
        
        # 服务器配置
        self.MOCK_WX_HOST = os.getenv('MOCK_WX_HOST', 'localhost')
        self.MOCK_WX_PORT = int(os.getenv('MOCK_WX_PORT', '8080'))
        self.MOCK_WX_DEBUG = os.getenv('MOCK_WX_DEBUG', 'true').lower() == 'true'
        
        # 数据存储配置
        self.MOCK_DATA_STORAGE = os.getenv('MOCK_DATA_STORAGE', 'memory')
        self.MOCK_DATA_FILE_PATH = os.getenv('MOCK_DATA_FILE_PATH', './mock_data.json')
        
        # 日志配置
        self.MOCK_LOG_LEVEL = os.getenv('MOCK_LOG_LEVEL', 'INFO')
        self.MOCK_LOG_FILE = os.getenv('MOCK_LOG_FILE', './logs/mock_wx_api.log')
        
        # Webhook配置
        self.WEBHOOK_URL = os.getenv('WEBHOOK_URL', 'http://localhost:5005/webhook')
        self.WX_TOKEN = os.getenv('WX_TOKEN', 'Sv3mVW1LOIU')
        self.WX_AES_KEY = os.getenv('WX_AES_KEY', 'NgHrjQdRw46FQIyTedXxJu6GrjqcoewHWlCQVLA76Ai')
        self.WEBHOOK_ENABLE_CALLBACK = os.getenv('WEBHOOK_ENABLE_CALLBACK', 'true').lower() == 'true'
        
        # 尝试从配置文件加载
        config_file = os.getenv('MOCK_CONFIG_FILE', './config.json')
        if os.path.exists(config_file):
            try:
                with open(config_file, 'r', encoding='utf-8') as f:
                    config_data = json.load(f)
                    self._update_from_dict(config_data)
            except Exception as e:
                print(f"加载配置文件失败: {e}")
    
    def _update_from_dict(self, config_dict: Dict[str, Any]):
        """从字典更新配置"""
        # 处理嵌套的配置结构
        if 'mock' in config_dict:
            mock_config = config_dict['mock']
            if 'corp_id' in mock_config:
                self.MOCK_WX_CORP_ID = mock_config['corp_id']
            if 'corp_secret' in mock_config:
                self.MOCK_WX_CORP_SECRET = mock_config['corp_secret']
            if 'open_kf_id' in mock_config:
                self.MOCK_OPEN_KF_ID = mock_config['open_kf_id']
            if 'token_expires' in mock_config:
                self.MOCK_TOKEN_EXPIRES = mock_config['token_expires']
            if 'enable_logging' in mock_config:
                self.MOCK_ENABLE_LOGGING = mock_config['enable_logging']
        
        if 'server' in config_dict:
            server_config = config_dict['server']
            if 'host' in server_config:
                self.MOCK_WX_HOST = server_config['host']
            if 'port' in server_config:
                self.MOCK_WX_PORT = server_config['port']
            if 'debug' in server_config:
                self.MOCK_WX_DEBUG = server_config['debug']
        
        if 'webhook' in config_dict:
            webhook_config = config_dict['webhook']
            if 'url' in webhook_config:
                self.WEBHOOK_URL = webhook_config['url']
            if 'token' in webhook_config:
                self.WX_TOKEN = webhook_config['token']
            if 'encoding_aes_key' in webhook_config:
                self.WX_AES_KEY = webhook_config['encoding_aes_key']
            if 'enable_callback' in webhook_config:
                self.WEBHOOK_ENABLE_CALLBACK = webhook_config['enable_callback']
        
        if 'data' in config_dict:
            data_config = config_dict['data']
            if 'storage_type' in data_config:
                self.MOCK_DATA_STORAGE = data_config['storage_type']
            if 'file_path' in data_config:
                self.MOCK_DATA_FILE_PATH = data_config['file_path']
        
        if 'logging' in config_dict:
            logging_config = config_dict['logging']
            if 'level' in logging_config:
                self.MOCK_LOG_LEVEL = logging_config['level']
            if 'file' in logging_config:
                self.MOCK_LOG_FILE = logging_config['file']
    
    def get_config_dict(self) -> Dict[str, Any]:
        """获取配置字典"""
        return {
            'MOCK_WX_CORP_ID': self.MOCK_WX_CORP_ID,
            'MOCK_WX_CORP_SECRET': self.MOCK_WX_CORP_SECRET,
            'MOCK_OPEN_KF_ID': self.MOCK_OPEN_KF_ID,
            'MOCK_TOKEN_EXPIRES': self.MOCK_TOKEN_EXPIRES,
            'MOCK_ENABLE_LOGGING': self.MOCK_ENABLE_LOGGING,
            'MOCK_WX_HOST': self.MOCK_WX_HOST,
            'MOCK_WX_PORT': self.MOCK_WX_PORT,
            'MOCK_WX_DEBUG': self.MOCK_WX_DEBUG,
            'MOCK_DATA_STORAGE': self.MOCK_DATA_STORAGE,
            'MOCK_DATA_FILE_PATH': self.MOCK_DATA_FILE_PATH,
            'MOCK_LOG_LEVEL': self.MOCK_LOG_LEVEL,
            'MOCK_LOG_FILE': self.MOCK_LOG_FILE,
            'WEBHOOK_URL': self.WEBHOOK_URL,
            'WX_TOKEN': self.WX_TOKEN,
            'WX_AES_KEY': self.WX_AES_KEY,
            'WEBHOOK_ENABLE_CALLBACK': self.WEBHOOK_ENABLE_CALLBACK
        }
